package cn.shiro.shiroservice.common.utils;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * &#064;Time 2024 一月 星期二 21:58
 *
 * @author ShangGuan
 */
public class HttpServletResponseUtils extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
        //this.getServletContext().getRealPath("/"); // 获取 服务器中当前WebRoot的物理路径
        response.setContentType("application/json;charset=utf-8");//设置编码格式，以防浏览器端出现中文乱码
        PrintWriter printWriter = response.getWriter();//创建输出流
        R<String> init = R.ok("init");
        String jsonString = JSON.toJSONString(init);
        printWriter.write(jsonString);
        printWriter.flush();
    }


    public static void write(String msg, HttpServletResponse response) {
        // 发生异常时，将错误信息写回给前端
        response.setStatus(response.getStatus());
        response.setContentType("application/json;charset=UTF-8");
        try {
            // 使用 PrintWriter 写回响应
            PrintWriter writer = response.getWriter();
            writer.write(msg);
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
